<template>
    <!-- 折叠/展开侧边栏按钮 -->
    <el-button type="primary" :icon="icons" @click="toggleCollapse" />
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="crumbs">
        <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item v-for="item in crumbsPath">{{ item }}</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 头像下拉菜单 -->
    <el-dropdown class="buddha">
        <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
        <template #dropdown>
            <el-dropdown-menu>
                <el-dropdown-item @click="skip(`/dashboard/user/profile/1`)">个人中心</el-dropdown-item>
                <el-dropdown-item @click="isEditHead = true">修改头像</el-dropdown-item>
                <el-dropdown-item divided @click="skip(`/`)">退出登录</el-dropdown-item>
            </el-dropdown-menu>
        </template>
    </el-dropdown>

    <!-- 修改头像弹窗 -->
    <el-dialog v-model="isEditHead" title="修改头像" width="500" align-center>
        <el-upload
            class="upload-demo"
            drag
            action="你的上传接口"
            multiple
            :limit="1"
            accept=".jpg,.png"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
        >
            <el-icon class="el-icon--upload">
                <upload-filled />
            </el-icon>
            <div class="el-upload__text">
                请拖拽上传 或 <em>点击上传</em> 文件
            </div>
            <template #tip>
                <div class="el-upload__tip">
                    注：只能上传 jpg/png 文件，且不超过 500kb
                </div>
            </template>
        </el-upload>
    </el-dialog>
</template>

<script setup>
// 引入 Element Plus 组件
import { ElButton, ElBreadcrumb, ElBreadcrumbItem, ElDropdown, ElDropdownMenu, ElDropdownItem, ElAvatar, ElDialog, ElUpload, ElIcon, ElMessage } from 'element-plus'
import { Expand, Fold, UploadFilled } from '@element-plus/icons-vue'
import { ref, computed, watch, onMounted } from 'vue'
import { debounce } from '@/tools/debounce.js'
import { useRoute, useRouter } from 'vue-router'

// 侧边栏折叠状态
const isCollapse = ref(false)
// 动态切换折叠/展开图标
const icons = computed(() => isCollapse.value ? Expand : Fold)
const route = useRoute()
const router = useRouter()
// 路由路径与中文名映射
const pathMapping = {
    user: '用户管理',
    role: '角色管理',
    content: '内容管理',
    data: '数据管理',
    system: '系统管理',
    settings: '系统设置',
    logs: '日志管理',
    profile: '个人中心',
    edit: '内容详情',
    detail: '数据详情'
}
let crumbsPath = ref([]) // 面包屑路径
const windowWidth = ref(window.innerWidth)
const emit = defineEmits(['getIsCollapse'])
const isEditHead = ref(false) // 控制头像弹窗显示

// 改变侧边栏状态的方法
function toggleCollapse() {
    isCollapse.value = !isCollapse.value
    giveIsCollapse()
}

// 自定义事件，向父组件传递侧边栏状态
const giveIsCollapse = () => {
    emit('getIsCollapse', isCollapse.value)
}

// 监听路由变化，动态生成面包屑
watch(() => route.path, () => {
    crumbsPath.value = route.path
        .split('/')
        .filter(item => item !== '' && item !== 'dashboard' && isNaN(+item))
        .map(path => pathMapping[path] || path)
}, { immediate: true })

// 组件挂载时监听窗口大小变化
onMounted(() => {
    window.addEventListener('resize', debounce(() => windowWidth.value = window.innerWidth, 200))
})

// 监听窗口宽度变化，自动折叠侧边栏
watch(windowWidth, newWidth => {
    if (newWidth < 768) {
        isCollapse.value = true
    } else {
        isCollapse.value = false
    }
    giveIsCollapse()
}, { immediate: true })

// 路由跳转
function skip(path) {
    router.push(path)
}

// 上传成功回调
const handleSuccess = response => {
    isEditHead.value = false
    ElMessage.success('上传成功！')
    console.log('后端返回的数据：', response)
}

// 上传失败回调
const handleError = () => {
    ElMessage.error('上传失败！')
}

// 文件上传前校验
const beforeUpload = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt500kb = file.size / 1024 / 1024 < 0.5

    if (!isJpgOrPng) {
        ElMessage.error('只能上传 JPG 或 PNG 文件')
        return false
    }
    if (!isLt500kb) {
        ElMessage.error('文件大小不能超过 500kb')
        return false
    }
    return true
}

// 超出文件数限制回调
const handleExceed = () => {
    ElMessage.warning('超出文件数限制，最多只能上传一个文件')
}

// 文件移除回调
const handleRemove = () => {
    ElMessage.info('文件已移除')
}
</script>

<style scoped>
.crumbs {
    margin-left: 1%;
}

.buddha {
    position: absolute;
    right: 1%;
    cursor: pointer;
}
</style>